package com.domainchen.framework.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月11日 下午2:03:44
 * @类说明 Json 工具
 */
public class JsonUtil {

	private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	/**
	 * POJO 转为Json
	 * 
	 * @param obj
	 * @return
	 */
	public static <T> String toJson(T obj) {
		String json = "";
		try {
			json = OBJECT_MAPPER.writeValueAsString(obj);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("conver POJO to Json failure", e);
			throw new RuntimeException(e);
		}
		return json;
	}

	/**
	 * json 转 POJO
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String json, Class<T> type) {
		T pojo = null;
		try {
			pojo = OBJECT_MAPPER.readValue(json, type);
		} catch (Exception e) {
			logger.error("conver POJO from JsonString failure", e);
			throw new RuntimeException(e);
		}
		return pojo;
	}

	
}
